package com.borrowed.book.book.service;

import com.alibaba.fastjson.JSONObject;
import com.borrowed.book.book.Exception.UnexpectOrderException;
import com.borrowed.book.book.constant.BookConstant;
import com.borrowed.book.book.domain.BookOrderDetailDto;
import com.borrowed.book.book.domain.CardOrderDetailDto;
import com.borrowed.book.book.domain.DeliverGoodInDto;
import com.borrowed.book.book.domain.SelectPayOrderOutDto;
import com.borrowed.book.book.entity.domain.vo.ConfirmReceiptVo;
import com.borrowed.book.book.entity.domain.vo.PayOrderBaseInVo;
import com.borrowed.book.book.entity.domain.vo.PayOrderBaseOutVo;
import com.borrowed.book.book.entity.domain.vo.PayOrderCreateInVo;
import com.borrowed.book.book.mapper.SPayOrderDetailMapper;
import com.borrowed.book.book.mapper.SPayOrderMapper;
import com.borrowed.book.user.domain.SUser;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单抽象类
 */
@Service
public abstract class AbstractPayOrderService {
    @Autowired
    private SPayOrderMapper payOrderMapper;
    @Autowired
    private SPayOrderDetailMapper payOrderDetailMapper;

    //下订单前  订单信息初始化加载
    public abstract PayOrderBaseOutVo initialPayorderInfo(PayOrderBaseInVo payorderBaseInVo);
    //创建订单数据,返回订单号
    public abstract String createPayorder(PayOrderCreateInVo payOrderCreateInVo) throws UnexpectOrderException;
    //取消订单数据
    public abstract Boolean cancelPayorder(String orderNo);
    //根据当前用户查询用户订单信息
    public  List<SelectPayOrderOutDto> selectPayOrderByOrderStatus(String orderStatus) {
        SUser sysUser = (SUser) SecurityUtils.getSubject().getPrincipal();
        Map<String,Object> map=new HashMap<>();
        map.put("openid",sysUser.getOpenid());
        map.put("orderStatus",orderStatus);
        List<SelectPayOrderOutDto> data=payOrderMapper.selectPayOrder(map);
        for(SelectPayOrderOutDto  order:data){
            if(BookConstant.RENT_ORDER.equals(order.getOrderType())) {
                //图书租赁订单
                List<BookOrderDetailDto> detailData = payOrderDetailMapper.selectBookListByOrderNo(order.getOrderNo());
                order.setBookData(detailData);
            }else if(BookConstant.CARD_ORDER.equals(order.getOrderType())){
                //会员订单
                CardOrderDetailDto cardData=payOrderDetailMapper.selectCardByOrderNo(order.getOrderNo());
                order.setCardData(cardData);
            }
        }
        return data;
    }

    /**
     * 管理员 一览查询用户订单信息
     * @param orderStatus
     * @return
     */
    public List<SelectPayOrderOutDto> selectPayOrderAdmin(String orderStatus) {
        Map<String,Object> map=new HashMap<>();
        map.put("orderStatus",orderStatus);
        List<SelectPayOrderOutDto> data=payOrderMapper.selectPayOrder(map);
        for(SelectPayOrderOutDto  order:data){
            if(BookConstant.RENT_ORDER.equals(order.getOrderType())) {
                //图书租赁订单
                List<BookOrderDetailDto> detailData = payOrderDetailMapper.selectBookListByOrderNo(order.getOrderNo());
                order.setBookData(detailData);
            }else if(BookConstant.CARD_ORDER.equals(order.getOrderType())){
                //会员订单
                CardOrderDetailDto cardData=payOrderDetailMapper.selectCardByOrderNo(order.getOrderNo());
                order.setCardData(cardData);
            }
        }
        return data;
    }

    /**
     * 根据订单号查询订单详细
     *
     * @param
     */
    public SelectPayOrderOutDto selectPayOrderDetail(String orderNo) {
        SelectPayOrderOutDto  order=payOrderMapper.selectPayOrderById(orderNo);
        if(BookConstant.RENT_ORDER.equals(order.getOrderType())) {
            //图书租赁订单
            List<BookOrderDetailDto> detailData = payOrderDetailMapper.selectBookListByOrderNo(order.getOrderNo());
            order.setBookData(detailData);
        }else if(BookConstant.CARD_ORDER.equals(order.getOrderType())){
            //会员订单
            CardOrderDetailDto cardData=payOrderDetailMapper.selectCardByOrderNo(order.getOrderNo());
            order.setCardData(cardData);
        }
        return order;
    }

    /**
     * 发货，更新订单状态，更新物流信息
     *
     * @param param
     */
    public void deliverGood(DeliverGoodInDto param) throws IllegalAccessException {
        Map<String,Object> map=com.borrowed.book.system.util.BeanUtils.getObjectToMap(param);
        map.put("orderStatus",BookConstant.TO_RECEIVE_PAY);
        payOrderMapper.updateOrderTransport(map);
    }

    /**
     * 根据物流单号查询物流信息
     *
     * @param orderNo
     */
    public String getTransportInfo(String orderNo) throws IOException {
        SelectPayOrderOutDto  order=payOrderMapper.selectPayOrderById(orderNo);
        if(order.getTransportNo()==null||order.getTransportName()==null){
            return "物流公司或物流单号为空，无物流信息";
        }else {
            //请求URL
            //创建默认连接
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //创建HttpGet对象,处理get请求,转发到A站点
            HttpGet httpGet = new HttpGet("https://v2.alapi.cn/api/kd?token=SyFov2f0zPSf7qe4&number=" + order.getTransportNo() + "&com=" + order.getTransportName());
            //执行
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int code = response.getStatusLine().getStatusCode();
            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            //获取A站点返回的结果
            response.close();
            httpClient.close();
            return jsonObject.toJSONString();
        }
    }

    /**
     * 确认收货，更新订单状态
     *
     * @param param
     */
    public void ConfirmReceipt(ConfirmReceiptVo param) {
        Map<String,Object> map=com.borrowed.book.system.util.BeanUtils.getObjectToMap(param);
        map.put("orderStatus",BookConstant.TO_RETURN_PAY);
        payOrderMapper.updatePayOrderReceiveStatus(map);
    }


}
